import { IAssemblyDocTreeNode } from '@amcax/base';
import { useContext, useMemo } from 'react';
import { DocumentContext } from '../../../common/providers/documentProvider';

/**
 * Custom hook to get all flat parts from the document tree.
 * Returns an array of nodes with type 'part'.
 */
export function useFlatParts(): IAssemblyDocTreeNode[] {
  const { docTree } = useContext(DocumentContext);

  // Recursively flatten all parts
  const flatAllParts = (node: IAssemblyDocTreeNode): IAssemblyDocTreeNode[] => {
    let result: IAssemblyDocTreeNode[] = [];
    if (node.type === 'part') {
      result.push(node);
    }
    if (Array.isArray(node.children)) {
      node.children.forEach((c) => {
        result = result.concat(flatAllParts(c));
      });
    }
    return result;
  };

  return useMemo(() => (docTree ? flatAllParts(docTree) : []), [docTree]);
}
